package com.threefish.modules.report.provider;

import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import com.threefish.modules.report.entity.ReportFileDO;
import com.threefish.modules.report.service.ReportSettingService;
import org.nutz.dao.Cnd;
import org.nutz.lang.stream.StringInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/6
 */
@Component
public class DBReportProvider implements ReportProvider {

    private static final String PREFIX = "DB:";

    @Autowired
    ReportSettingService reportSettingService;


    private ReportFileDO get(String reportName) {
        reportName = reportName.replaceFirst(PREFIX, "");
        return reportSettingService.fetch(Cnd.where("reportName", "=", reportName));
    }

    /**
     * 根据报表名加载报表文件
     *
     * @param reportName 报表名称
     * @return 返回的InputStream
     */
    @Override
    public InputStream loadReport(String reportName) {
        return new StringInputStream(get(reportName).getReportContent());
    }

    /**
     * 根据报表名，删除指定的报表文件
     *
     * @param reportName 报表名称
     */
    @Override
    public void deleteReport(String reportName) {
        reportSettingService.delete(get(reportName));
    }

    /**
     * 获取所有的报表文件
     *
     * @return 返回报表文件列表
     */
    @Override
    public List<ReportFile> getReportFiles() {
        List<ReportFileDO> reportFileDOS = reportSettingService.query();
        List<ReportFile> reportFiles = new ArrayList<>();
        reportFileDOS.forEach(reportFileDO -> reportFiles.add(new ReportFile(reportFileDO.getReportName(), reportFileDO.getOpAt())));
        return reportFiles;
    }

    /**
     * 保存报表文件
     *
     * @param reportName 报表名称
     * @param content    报表的XML内容
     */
    @Override
    public void saveReport(String reportName, String content) {
        ReportFileDO reportFileDO = get(reportName);
        if (reportFileDO == null) {
            reportFileDO = new ReportFileDO();
            reportName = reportName.replaceFirst(PREFIX, "");
            reportFileDO.setReportName(reportName);
        }
        reportFileDO.setReportContent(content);
        reportSettingService.insertOrUpdate(reportFileDO);
    }

    /**
     * @return 返回存储器名称
     */
    @Override
    public String getName() {
        return "内置数据存储";
    }

    /**
     * @return 返回是否禁用
     */
    @Override
    public boolean disabled() {
        return false;
    }

    /**
     * @return 返回报表文件名前缀
     */
    @Override
    public String getPrefix() {
        return PREFIX;
    }

}
